<?php
class UsersController extends AppController{
     public $components = array(
        'Auth' => array(
            'loginAction' => array('controller'=>'users', 'action'=>'login'),
            'loginRedirect' => array('controller' => 'users', 'action' => 'index'),
            'logoutRedirect' => array('controller' => 'intro', 'action' => 'index'),
			'authError' => 'You must be logged in to view this page.',
			'loginError' => 'Invalid Username or Password entered, please try again.',
            'authenticate' => array(
                'Form' => array(
                    'fields' => array('username' => 'username', 'password' => 'password')
                )
            ),
        )
    ); 
    
    public function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allow('register');
    }
    
    public function login($contro = '')
    {
        if($this->Session->check('Auth.User')){
            if($contro == 'checkout')
                {
                    $this->redirect(array('controller' => 'checkout', 'action' => 'index', $this->Auth->user('username')));
                    exit;
                }
            $this->redirect(array('controller' => 'users', 'action' => 'index'));    
        }
        if ($this->request->is('post')) {
          if ($this->Auth->login()) {
                $info_user = AuthComponent::user();
                $this->Session->write('info_user',$info_user);
                /*
                $this->Session->setFlash(
                                'Đăng nhập thành công. Xin chào '.$this->Auth->user('name'),
                                'default',
                                array('class' => 'alert alert-success')
                            );
                */
                if($contro == 'checkout')
                {
                    $this->redirect(array('controller' => 'checkout', 'action' => 'index'));
                }
                else
                {
                    $this->redirect($this->Auth->redirectUrl());
                }
                
          } else {
                $this->Session->setFlash(
                                    'Sai tên đăng nhập hoặc mật khẩu',
                                    'default',
                                    array('class' => 'alert alert-danger')
                                ); 
          }
        } 
        $breadcrumbs[] = array('title' => 'Đăng nhập', 'link' => 'users/login');
        $this->set('breadcrumbs', $breadcrumbs);
        
        $meta_title = 'Đăng nhập';
        $this->set('meta_title', $meta_title);
        
        $has_html = '';
        $this->set('has_html', $has_html);
        $header_menu_sidebar['title'] = 'Đăng nhập';
        $header_menu_sidebar['link'] = 'users/login';
        $this->set('header_menu_sidebar', $header_menu_sidebar);
        $menu_sidebar = array();
        $this->set('menu_sidebar', $menu_sidebar);
    }
    
    public function register()
    {
        if($this->Session->check('Auth.User')){
          $this->redirect(array('controller' => 'users', 'action' => 'index'));    
        }
        
        if ($this->request->is('post')) {
        
          $date_birth = $this->request->data['User']['date_birth'];
          if($date_birth != '')
            $date_birth = substr($date_birth,6,4) .'-'. substr($date_birth,3,2) .'-'. substr($date_birth,0,2);
          else
            $date_birth = '0000-00-00';
            
          $username = $this->request->data['User']['username'];
          $password = AuthComponent::password($this->request->data['User']['password']);
          $name = $this->request->data['User']['name'];
          $email = $this->request->data['User']['email'];
          $address = $this->request->data['User']['address'];
          $gender = isset($this->request->data['User']['gender']) ? $this->request->data['User']['gender'] : '';
          $phone = $this->request->data['User']['phone'];
            
          $sql = "INSERT INTO users VALUES ('', '$username', '$password', '$name', '$email', now(), now(), 1, '$date_birth', '$address', '$gender', '$phone', 3)";

          try {
                $this->User->query($sql);
                $this->Session->setFlash(
                                'Đăng ký tài khoản thành công',
                                'default',
                                array('class' => 'alert alert-success')
                            );
            $this->redirect(array('controller'=>'users', 'action'=>'login'));
          } catch (Exception $e) {
                echo 'Caught exception: ',  $e->getMessage(), "\n";
                $this->Session->setFlash(
                                    'Đăng ký không thành công<br/>'.$e->getMessage(),
                                    'default',
                                    array('class' => 'alert alert-danger')
                                ); 
          }

        }
        

        $breadcrumbs[] = array('title' => 'Đăng ký', 'link' => 'users/register');
        $this->set('breadcrumbs', $breadcrumbs);
        
        $meta_title = 'Đăng ký';
        $this->set('meta_title', $meta_title);
        
        $has_html = '';
        $this->set('has_html', $has_html);
        $header_menu_sidebar['title'] = 'Đăng ký';
        $header_menu_sidebar['link'] = 'users/register';
        $this->set('header_menu_sidebar', $header_menu_sidebar);
        $menu_sidebar = array();
        $this->set('menu_sidebar', $menu_sidebar);
    }
    
    public function edit()
    {
        if(!$this->Session->check('Auth.User')){
          $this->redirect(array('controller' => 'users', 'action' => 'login'));    
        }
        
        $id = $this->Auth->user('id');
        $sql = array('conditions' => array('id =' => $id));
        $user_info = $this->User->find('all', $sql);
        $this->set('user_info', $user_info[0]['User']);
        
        if ($this->request->is('post')) {
        
          $date_birth = $this->request->data['User']['date_birth'];
          if($date_birth != '')
            $date_birth = substr($date_birth,6,4) .'-'. substr($date_birth,3,2) .'-'. substr($date_birth,0,2);
          else
            $date_birth = '0000-00-00';
            
          $name = $this->request->data['User']['name'];
          $address = $this->request->data['User']['address'];
          $gender = isset($this->request->data['User']['gender']) ? $this->request->data['User']['gender'] : '';
          $phone = $this->request->data['User']['phone'];
            
          $sql = "UPDATE users SET `name` = '$name',
                                    `address` = '$address',
                                    `gender` = '$gender',
                                    `phone` = '$phone',
                                    `date_birth` = '$date_birth' 
                WHERE id = $id";

          try {
                $this->User->query($sql);
                $this->Session->setFlash(
                                'Cập nhật tài khoản thành công',
                                'default',
                                array('class' => 'alert alert-success')
                            );
                $this->Session->write('info_user.name', $name);
                $this->Session->write('info_user.address', $address);
                $this->Session->write('info_user.gender', $gender);
                $this->Session->write('info_user.phone', $phone);
                $this->Session->write('info_user.date_birth', $date_birth);
                
            $this->redirect(array('controller'=>'users', 'action'=>'index'));
          } catch (Exception $e) {
                echo 'Caught exception: ',  $e->getMessage(), "\n";
                $this->Session->setFlash(
                                    'Cập nhật tài khoản không thành công<br/>'.$e->getMessage(),
                                    'default',
                                    array('class' => 'alert alert-danger')
                                ); 
          }

        }
        
        
        
        $breadcrumbs[] = array('title' => 'Sửa thông tin tài khoản', 'link' => 'users/edit');
        $this->set('breadcrumbs', $breadcrumbs);
        
        $meta_title = 'Sửa thông tin tài khoản';
        $this->set('meta_title', $meta_title);
        
        
        $has_html = '';
        $this->set('has_html', $has_html);
        $header_menu_sidebar['title'] = 'Sửa tài khoản';
        $header_menu_sidebar['link'] = 'users/edit';
        $this->set('header_menu_sidebar', $header_menu_sidebar);
        $menu_sidebar = array();
        $this->set('menu_sidebar', $menu_sidebar);  
    }
    
    
    public function register_bk()
    {
        if($this->Session->check('Auth.User')){
          $this->redirect(array('controller' => 'users', 'action' => 'index'));    
        }
        
        if ($this->request->is('post')) {
        
          $date_birth = $this->request->data['User']['date_birth'];
          if($date_birth != '')
            $date_birth = substr($date_birth,6,4) .'-'. substr($date_birth,3,2) .'-'. substr($date_birth,0,2);
          else
            $date_birth = '0000-00-00';
          $this->request->data['User']['date_birth'] = $date_birth;
          $this->User->create();
          if ($this->User->save($this->request->data)) {
            $this->Session->setFlash(
                                'Đăng ký tài khoản thành công',
                                'default',
                                array('class' => 'alert alert-success')
                            );
            $this->redirect(array('controller'=>'users', 'action'=>'login'));
          } else {
            $this->Session->setFlash(
                                    'Đăng ký không thành công',
                                    'default',
                                    array('class' => 'alert alert-danger')
                                ); 
          }
        }
    }
    
    public function index()
    {
        if(!$this->Session->check('Auth.User')){
          $this->redirect(array('controller' => 'users', 'action' => 'login'));    
        }
        
        $info_user = $this->Auth->user();
        $this->set('info_user', $info_user);
        
        $this->loadModel('Cart');                
        $email = @$info_user['email'];        
        $info_cart = $this->Cart->get_info_cart_by_email($email);
        $this->set('info_cart', $info_cart);    
        
        $breadcrumbs[] = array('title' => 'Thông tin tài khoản', 'link' => 'users/index');
        $this->set('breadcrumbs', $breadcrumbs);   
        
        $meta_title = 'Thông tin tài khoản';
        $this->set('meta_title', $meta_title);  
        
        $has_html = '';
        $this->set('has_html', $has_html);
        $header_menu_sidebar['title'] = 'Thông tin tài khoản';
        $header_menu_sidebar['link'] = 'users';
        $this->set('header_menu_sidebar', $header_menu_sidebar);
        $menu_sidebar = array();
        $this->set('menu_sidebar', $menu_sidebar);       
    }
    
    
    public function logout()
    {
        $this->Session->delete('info_user');
        $this->redirect($this->Auth->logout());
    }
    
    public function change_password()
    {
        if(!$this->Session->check('Auth.User')){
          $this->redirect(array('controller' => 'users', 'action' => 'login'));    
        }
        
        if ($this->request->is('post')) {
            $password = AuthComponent::password($this->request->data['User']['password']);
            $password_update = AuthComponent::password($this->request->data['User']['password_update']);
            $id = $this->Auth->user('id');
            $sql = array('conditions' => array('id =' => $id, 'password =' => $password));
            $data = $this->User->find('all', $sql);
            if(!empty($data))
            {
                $sql = "UPDATE users SET `password` = '$password_update' WHERE id = $id";
                $this->User->query($sql);
                $this->Session->setFlash(
                                'Thay đổi mật khẩu thành công',
                                'default',
                                array('class' => 'alert alert-success')
                            );
                $this->redirect(array('action' => 'index'));
            }
            else
            {
                $this->Session->setFlash(
                                    'Mật khẩu cũ không đúng.',
                                    'default',
                                    array('class' => 'alert alert-danger')
                                );
            }
        }
        
        $breadcrumbs[] = array('title' => 'Thay đổi mật khẩu', 'link' => 'users/change_password');
        $this->set('breadcrumbs', $breadcrumbs);   
        
        $meta_title = 'Thay đổi mật khẩu';
        $this->set('meta_title', $meta_title); 
        
        $has_html = '';
        $this->set('has_html', $has_html);
        $header_menu_sidebar['title'] = 'Thay đổi mật khẩu';
        $header_menu_sidebar['link'] = 'users/change_password';
        $this->set('header_menu_sidebar', $header_menu_sidebar);
        $menu_sidebar = array();
        $this->set('menu_sidebar', $menu_sidebar);  
    }
    
    
}
    